<?php

/**
 * 关联预载入
 * 关联统计和输出
 */
namespace app\controller;


use app\model\User;

class Load
{
    public function index(){
//        $users = User::select([19,20,21]);
        //关联预载入模式减少了查询次数 提高性能，但不支持多次调用
//        $users = User::with(['book'])->select([19,20,21]);
//        foreach ($users as $user){
//            dump($user->book->toArray());
//        }

//        $users = User::with(['book','profile'])->select([19,20,21]);
//        foreach ($users as $user){
//            dump($user->book.$user->profile);
//        }

//         $users = User::with(['book'=>function($query){
//             $query->field('user_id,title');
//         }])->select([19,20]);


         //关联延迟预载入
        $users = User::select([19,20]);

        $users->load(['book']);
        foreach ($users as $user){
            dump($user->book->toArray());
        }
    }

    public function count(){

        //使用withCount()方法，可以统计主表关联附表的个数，使用"关联方法名"._count输出
//        $users  =User::withCount(['book'])->select([19,20,21]);
//        foreach($users as $user){
//            echo $user->book_count.'<br>';
//        }
        // 也支持withMax withMin withSum withAvg
        //除了wirhCount()不需要指定字段，其他都需要指定统计字段
//        $users = User::withSum(['profile'],'status')->select([19,20,21]);
//        foreach ($users as $user){
//            echo $user->profile_sum."<br>";
//        }


//        $user = User::with(['book'])->select();
//        //hidden()隐藏主表字段和附属表字段
//        return json($user->hidden(['username','book'=>['id','user_id']]));
        //visible() 只显示相关字段
        //append() 添加一个额外字段，比如另一哥关联对象的模型
        $user = User::with(['book'])->select();
        return json($user->append(['profile']));
    }
}